<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import {ElMessage, ElMessageBox, ElTag} from 'element-plus'
import { Table } from '@/components/Table'
import { delTableListApi } from '@/api/table'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { reactive, ref, unref } from 'vue'
import { useRouter } from 'vue-router'
import { useEventBus } from '@/hooks/event/useEventBus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import {deletePatientApi, patientListApi} from "@/api/patient";
import {PatientQueryParams, PatientType} from "@/api/patient/types";

defineOptions({
  name: 'ExamplePage'
})

const { push } = useRouter()

const ids = ref<string[]>([])

const params: PatientQueryParams = {
  page: 1,
  page_size: 10,
}
const setSearchParams = (formData: any) => {
  params.card_number = formData.card_number
  params.patient_number = formData.patient_number
  params.name = formData.name
  refresh()
}
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    loading.value = true
    const { currentPage, pageSize } = tableState
    params.page = unref(currentPage)
    params.page_size = unref(pageSize)
    const res = await patientListApi(params).finally(()=>loading.value = false)
    return {
      list: res.data,
      total: res.total
    }
  },
  fetchDelApi: async () => {
    await delTableListApi(unref(ids))
    return true
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, refresh } = tableMethods
getList()

useEventBus({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: 'ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'patient_number',
    label: '病案号',
  },
  {
    field: 'card_number',
    label: '身份证'
  },
  {
    field: 'name',
    label: '患者姓名'
  },
  {
    field: 'gender',
    label: '患者性别',
    search:{
      hidden: true,
    },
    slots: {
      default: (scope: any) => {
        const row = scope.row
        return <ElTag>{row.gender == 1 ? '男' : '女'}</ElTag>
      }
    }
  },
  // {
  //   field: 'age',
  //   label: '患者年龄',
  //   search: {
  //     hidden: true,
  //   }
  // },
  {
    field: 'action',
    width: '260px',
    label: '操作',
    fixed: 'right',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <BaseButton type="success" onClick={() => action(data.row, 'detail')}>
              查阅
              </BaseButton>
              <BaseButton type="primary" onClick={() => action(data.row, 'edit')} roles={[2, 99]}>
             编辑
              </BaseButton>
              <BaseButton type="danger" onClick={() => delData(data.row)} roles={[2, 99]}>
              删除
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const AddAction = () => {
  push('/patient/add')
}

const delLoading = ref(false)

const delData = async (row: PatientType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  await ElMessageBox.confirm("确认删除选中数据吗", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: 'warning'
  })
  let arr: any[] = []
  ids.value.forEach(id=>{
    arr.push(deletePatientApi(parseInt(id)))
  })
  delLoading.value = true
  // 同步执行所有删除
  await Promise.all(arr)
  delLoading.value = false
  ElMessage.success("删除成功")
  refresh()
}

const action = (row: TableData, type: string) => {
  if (type === 'edit'){
    push(`/patient/edit?id=${row.id}`)
  }else{
    push(`/patient/detail?id=${row.id}`)
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction" :roles="[2, 99]">新增</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)" :roles="[2, 99]">
        删除
      </BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
@/hooks/event/useEventBus
